<template>
  <div>
    <myDivider name="部门管理"></myDivider>
    <div style="width: 100%;margin-left: 20px;">
      <el-input style="width: 200px;" maxlength="100" v-model="query.depName" placeholder="根据部门名称搜索"
        @keyup.enter.native="SouSuo" clearable></el-input>
      <el-select style="width: 150px;" placeholder="请选择账号类型" v-model="query.userType" clearable @change="SouSuo">
        <el-option v-for="item, i in unitTypeData" :key="i" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-button type="primary" style=" margin-left: 15px" @click="SouSuo">查询</el-button>
      <el-button style=" margin-left: 15px" @click="Reset">重置</el-button>
      <div style="margin-top: 10px;">
        <el-button type="primary" @click="addClick">新增</el-button>
      </div>
    </div>
    <div class="TableStyle1">
      <el-table @filter-change="filterChange" :data="departmentData" style="width: 100%" class="menuTable" row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <!-- <el-table-column prop="id" label="部门名称" width="">
        </el-table-column> -->
        <el-table-column prop="name" label="部门名称" width="200px" align="left">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.name" placement="top-start">
              <span>{{ scope.row.name == null ? '—' : scope.row.name.length > 8 ?
        "..." + scope.row.name.substring(scope.row.name.length - 8,
          scope.row.name.length) : scope.row.name }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="unitTypeName" width="150px" column-key="unitTypeName" label="类型" align="center"
          :filters="[{ text: '机关', value: 'agency' }, { text: '机构', value: 'company' }]" :filter-multiple="false">
        </el-table-column>
        <el-table-column prop="unitName" column-key="unitName" label="单位名称" width="350px" align="center"
          :filters="[{ text: 'aa', value: 'aa' }, { text: 'bb', value: 'bb' }]" :filter-multiple="false">
        </el-table-column> -->
        <el-table-column prop="unitName" column-key="unitName" label="所属单位" width="250px" align="center">
        </el-table-column>
        <el-table-column prop="unitTypeName" label="单位类型" align="center">
        </el-table-column>

        <el-table-column prop="description" label="部门描述" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.description" placement="top-start">
              <span>{{ scope.row.description == null ? '—' : scope.row.description.length > 8 ?
        "..." + scope.row.description.substring(scope.row.description.length - 8,
          scope.row.description.length) : scope.row.description }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="userCount" label="部门人数" width="200px" align="center">
          <template slot-scope="scope">
            {{ scope.row.unitType == 'agency' ? scope.row.agencyCount : scope.row.unitType
        == 'company' ? scope.row.companyCount : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200px" align="center">
        </el-table-column>
        <el-table-column label="操作" width="100px" align="center">
          <template slot-scope="scope">

            <div class="textBtn" style="display: flex;justify-content: space-between;align-items: center;">
              <span style="color: #5fadff;cursor: pointer;font-weight: 600;flex: 1;"
                @click="updateClick(scope.row)">修改</span>
              <span style="color: #5fadff;cursor: pointer;font-weight: 600;flex: 1;"
                @click="deleteClick(scope.row)">删除</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <!-- 新增部门 -->
    <el-dialog :close-on-click-modal="false" class="dialogStyle" width="600px"
      :title="AddDepartmentScene === 'add' ? '添加部门' : '修改部门'" :visible.sync="AddDepartmentShow">

      <el-divider></el-divider>
      <el-form :model="insertForm" :rules="insertRules" ref="insertForm">


        <el-form-item label="部门名称:" label-width="120px" class="formItemStyle" prop="name">
          <el-input maxlength="50" placeholder="请输入部门名称" v-model="insertForm.name" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="所属单位:" label-width="120px" class="formItemStyle">
          <div style="display: flex;">
            <el-button style="margin-right: 10px" size="small" type="" @click="toSelectDepartment">选择</el-button>
            <el-input style="width: 196px;" v-model="insertForm.unitName" placeholder="请点击按钮选择" disabled></el-input>
          </div>
        </el-form-item>
        <el-form-item label="描述:" label-width="120px" class="formItemStyle">
          <el-input type="textarea" placeholder="请输入内容" v-model="insertForm.description" maxlength="100"
            style="width: 262px" show-word-limit>
          </el-input>
        </el-form-item>

        <el-form-item label="父级部门:" label-width="120px" class="formItemStyle">
          <div class="block">
            <el-cascader :key='selectIndex' @change="pidsChange" style="width: 262px" v-model="insertForm.pids"
              placeholder="请先选择单位" :options="fatherDepmentManageData" filterable ref="pidsCascader"
              :props="{ checkStrictly: true }" clearable></el-cascader>
          </div>
        </el-form-item>

      </el-form>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="AddDepartmentShow = false">取 消</el-button>
        <el-button type="primary" @click="AddDepartmentOk('insertForm')">确
          定</el-button>
      </div>

    </el-dialog>



    <!-- 选择单位弹窗 -->
    <el-dialog class="dialogStyle" :close-on-click-modal="false" width="600px" title="选择单位"
      :visible.sync="selectDepartmentPopShow">
      <el-divider></el-divider>
      <!-- 筛选项 -->
      <div style="display: flex;justify-content: space-between;margin: 20px 0;">
        <el-input size="medium" maxlength="20" style="width: 200px;" v-model="selectDepartmentPopKeyName"
          placeholder="根据社区名称搜索"></el-input>
        <el-select @change="getSelectDepartmentPopData" size="medium" style="width: 262px" placeholder="请选择所属单位"
          v-model="selectDepartmentPopKeyType" clearable>
          <el-option v-for="item, i in unitTypeData" :key="i" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-button size="medium" type="primary" @click="getSelectDepartmentPopData">查询</el-button>

      </div>

      <div class="TableStyle">
        <el-table ref="selectDepartmentPopTable" @current-change="selectDepartmentPopChange"
          :data="selectDepartmentPopData" style="width: 100%" height="400px" highlight-current-row>

          <el-table-column align="center" prop="unitName" label="单位名称">
          </el-table-column>
          <el-table-column align="center" prop="unitType" label="单位类型" width="180">
            <template slot-scope="scope">
              {{ scope.row.unitType == 'agency' ? '机关' : scope.row.unitType
        == 'company' ? '机构' : '系统' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="selectDepartmentPopShow = false">取 消</el-button>
        <el-button type="primary" @click="selectDepartmentPopOk">确
          定</el-button>
      </div>

    </el-dialog>


    <myPagination :total="total" :pageNum="pageNum" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
  </div>
</template>





<script>
import { effectScope } from "vue";
import {
  insertDepartment,
  getDepartmentList,
  getFatherDepList,
  deleteDepartmentById,
  getDepInfoById,
  getUserListByDepId,
  updateDeparement

} from "./department";
export default {


  data() {
    return {
      selectIndex: 0,
      props: {
        checkStrictly: true,
        value: 'id',
        label: 'name',
      },
      departmentData: [], //列表数据
      fatherDepmentManageData: [],
      query: {}, //搜索条件
      insertForm: {},
      insertRules: {
        name: [{ required: true, message: "部门名称不能为空", trigger: "blur", },],
      },

      pageNum: 1,
      pageSize: 10,
      total: 0,

      // 列表筛选项
      unitTypeName: '',
      unitName: '',

      logOnUserData: {},//登录用户信息
      unitTypeData: [],
      // 新版 新增部门弹窗
      AddDepartmentShow: false, //控制弹框开关
      AddDepartmentScene: '',
      // 选择单位弹窗
      selectDepartmentPopShow: false,//选择角色弹窗显隐
      selectDepartmentPopTableShow: false,// 选择角色的table显隐
      selectDepartmentPopKeyName: '',
      selectDepartmentPopKeyType: '',
      selectDepartmentCache: {},//缓存
      selectDepartmentPopData: [],
    };
  },
  watch: {
    wayOptions(newVal) {
      this.selectIndex++
    },
    deep: true
  },
  activated() {
    this.logOnUserData = JSON.parse(sessionStorage.getItem('logOnUser'))
    switch (this.logOnUserData.unitType) {
      case 'system':
        this.unitTypeData = [
          { label: '系统管理员', value: 'system' },
          { label: '机关管理员', value: 'agency' },
          { label: '机构管理员', value: 'company' },
        ]
        break
      case 'agency':
        this.unitTypeData = [
          { label: '机关管理员', value: 'agency' },
        ]
        break
      case 'company':
        this.unitTypeData = [
          { label: '机构管理员', value: 'company' },
        ]
        break
    }
    this.$set(this.query, 'depName', '')
    this.$set(this.query, 'userType', '')
    this.queryDepartmentList()
  },
  methods: {
    pidsChange(val) {
      if (val.length == 0) return
      if (val.length == 3) {
        this.$message.error('不能选择超过三级')
        this.$set(this.insertForm, 'pids', [])
        return
      }
      // const checkedNodes = this.$refs['pidsCascader'].getCheckedNodes()
      // this.insertForm.level = checkedNodes[0].level
    },
    //新增 / 修改 / 删除 按钮 ======================
    addClick(type) {
      this.AddDepartmentShow = true //打开弹窗
      this.AddDepartmentScene = 'add'



      //清空数据
      this.$set(this.insertForm, 'name', '')
      this.$set(this.insertForm, 'description', '')
      this.$set(this.insertForm, 'pids', [])
      this.$set(this.insertForm, 'unitName', '')
      this.$set(this.insertForm, 'unitId', '')
      this.$set(this.insertForm, 'unitType', '')

      this.selectDepartmentPopKeyName = ''
      this.selectDepartmentPopKeyType = this.logOnUserData.unitType
      this.fatherDepmentManageData = []

      this.$nextTick(() => {
        this.$refs.insertForm.clearValidate()
      })



    },
    async updateClick(row) {

      this.AddDepartmentScene = 'update'
      this.AddDepartmentShow = true


      getDepInfoById(row.id).then((res) => { //获取详情
        console.log(res,'resdqw')
        // 获取父级列表
        getFatherDepList(res.unitType, res.unitId,res.id).then((ress) => {
          this.fatherDepmentManageData = ress;
        });
        this.$set(this.insertForm, 'id', res.id)
        this.$set(this.insertForm, 'name', res.name)
        this.$set(this.insertForm, 'description', res.description)
        this.$set(this.insertForm, 'unitName', res.unitName)
        this.$set(this.insertForm, 'unitId', res.unitId)
        this.$set(this.insertForm, 'unitType', res.unitType)
        this.$set(this.insertForm, 'pids', JSON.parse(res.pids))
        this.selectDepartmentPopKeyName = ''
        this.selectDepartmentPopKeyType = res.unitType

        this.$nextTick(() => {
          this.$refs.insertForm.clearValidate()
        })
      });
    },
    deleteClick(row) {

      var id = row.id;
      //先去请求部门下是否有用户
      getUserListByDepId(id).then((res) => {
        if (res.code == 200) {
          if (res.data.length > 0) {
            this.$confirm("部门下存在员工，删除部门自动与员工取消关联并删除子部门，是否删除", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.confirmToDelete(id);
            }).catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
              return;
            });
          } else {
            this.$confirm("确认删除该部门吗?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              this.confirmToDelete(id);

            }).catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
              return;
            });
          }
        }
      })
    },
    //新增 / 修改 / 删除 按钮 ======================


    // 添加部门弹窗 ===========================================
    AddDepartmentOk(name) { //添加部门弹窗点击确定
      this.$refs[name].validate(async (valid) => {
        if (valid) {

          if (this.insertForm.pids != null && this.insertForm.pids.length != 0) {
            this.insertForm.pid = this.insertForm.pids[this.insertForm.pids.length - 1];
          } else {
            this.insertForm.pid = 0
          }

          switch (this.AddDepartmentScene) {
            case 'add':
              let res = await this.$api.system.myInsertDepartment({
                "name": this.insertForm.name, //部门名称
                "description": this.insertForm.description, //部门描述
                // "level": this.insertForm.level,
                "pid": this.insertForm.pid,
                "pids": JSON.stringify(this.insertForm.pids),
                "unitType": this.insertForm.unitType, //和所属单位保持一致 机关:agency,机构:company  系统system
                "unitId": this.insertForm.unitId //和所属单位保持一致，系统传0
              })

              if (res.code == 200) {
                this.$message({
                  message: "添加成功",
                  type: "success",
                });
                this.AddDepartmentShow = false;
                this.queryDepartmentList();
              } else {
                this.$message({
                  message: res.message,
                  type: "warning",
                });
              }
              break
            case 'update':
              console.log(this.insertForm, 'insertForm');
              let updateRes = await this.$api.system.myUpdateDepartment({
                "id": this.insertForm.id,
                "name": this.insertForm.name, //部门名称
                "description": this.insertForm.description, //部门描述
                // "level": this.insertForm.level,
                "pid": this.insertForm.pid,
                "pids": JSON.stringify(this.insertForm.pids),
                "unitType": this.insertForm.unitType, //和所属单位保持一致 机关:agency,机构:company  系统system
                "unitId": this.insertForm.unitId //和所属单位保持一致，系统传0
              })
              if (updateRes.code == 200) {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.AddDepartmentShow = false;
                this.queryDepartmentList();
              } else {
                this.$message({
                  message: updateRes.message,
                  type: "warning",
                });
              }
              break
          }





        }
      });
    },
    toSelectDepartment() { // 点击选择 打开选择单位弹窗
      this.selectDepartmentPopShow = true
      this.getSelectDepartmentPopData()
    },
    // 添加部门弹窗 ===========================================


    // 选择单位 ==============================================
    async getSelectDepartmentPopData() { //搜索用户列表
      let logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
      let res = await this.$api.system.myGetUnitByType({
        "name": this.selectDepartmentPopKeyName, //单位名称
        "unitId":logOnUser.unitId,
        "unitType": this.selectDepartmentPopKeyType //单位类型 可不填
      })
      console.log(res, '选择角色的角色列表');
      if (res.code == 200) {
        this.selectDepartmentPopData = res.data
        this.$nextTick(() => {
          this.$refs.selectDepartmentPopTable.setCurrentRow([]);
        })
        if (this.insertForm.unitId.length == 0) { //如果没有值，清空缓存
          this.selectDepartmentCache = {}
          return
        }
        this.$nextTick(() => { //有值就激活选中项
          this.selectDepartmentPopData.forEach((el, i) => {
            if (el.unitId == this.insertForm.unitId) {
              this.$refs.selectDepartmentPopTable.setCurrentRow(this.selectDepartmentPopData[i]);
            }
          })
        })
      } else {
        this.$message.error(res.message)
      }
    },
    selectDepartmentPopOk() {

      this.selectDepartmentPopShow = false
      this.insertForm.unitId = this.selectDepartmentCache.unitId
      this.insertForm.unitType = this.selectDepartmentCache.unitType
      this.insertForm.unitName = this.selectDepartmentCache.unitName

      getFatherDepList(this.insertForm.unitType, this.insertForm.unitId,0).then((ress) => {
        this.fatherDepmentManageData = ress;
      });
      // 获取父级部门数据
      // getDepartmentList('', 1, 1000, this.insertForm.unitType, this.insertForm.unitId).then((res) => {
      //   let arr = []
      //   res.list.forEach(el => {
      //     arr.push(el)
      //   })
      //   this.fatherDepmentManageData = arr
      // });
      this.insertForm.pids = []
    },
    selectDepartmentPopChange(val) {
      this.selectDepartmentCache = val

    },
    // 选择单位 ===========================================
    filterChange(val) { //表格筛选函数
      // if ('unitTypeName' in val) {
      //   if (val.unitTypeName.length == 0) {
      //     this.unitTypeName = ''
      //     this.pageNum = 1
      //     this.queryDepartmentList()
      //     return
      //   } else {
      //     this.unitTypeName = val.unitTypeName[0]
      //     this.queryDepartmentList()
      //   }
      // }
      // if ('unitName' in val) {
      //   if (val.unitName.length == 0) {
      //     this.unitName = ''
      //     this.pageNum = 1
      //     this.queryDepartmentList()
      //     return
      //   } else {
      //     this.unitName = val.unitName[0]
      //     this.queryDepartmentList()
      //   }
      // }
    },
    PageChange(e) {
      this.pageNum = e
      this.queryDepartmentList()
    },
    pageSizeChange(e) {
      this.pageNum = 1
      this.pageSize = e
      this.queryDepartmentList()
    },
    SouSuo() {
      this.pageNum = 1
      this.queryDepartmentList()
    },
    Reset() {
      this.pageNum = 1
      this.$set(this.query, 'depName', '')
      this.$set(this.query, 'userType', '')
      this.queryDepartmentList()
    },
    //按条件查询菜单列表
    async queryDepartmentList() {
      let userData = JSON.parse(sessionStorage.getItem('logOnUser'))
      let params
      if (userData.unitType == 'system') {
        params = {
          "name": this.query.depName,
          "unitType": userData.unitType, //必填 机关：agency  机构：company  系统：system 
          "unitId": userData.unitId, //系统传0，查所有也传0
          "paramUnitType": this.query.userType, //查所有""(只有系统用户才有此参数)  机关：agency  机构：company  系统：system 
          "pageNum": this.pageNum,
          "pageSize": this.pageSize
        }
      } else {
        params = {
          "name": this.query.depName,
          "unitType": userData.unitType, //必填 机关：agency  机构：company  系统：system 
          "unitId": userData.unitId, //系统传0，查所有也传0
          "pageNum": this.pageNum,
          "pageSize": this.pageSize
        }
      }
      let res = await this.$api.system.myGetDepartmentList(params)
      console.log(res, '列表');
      if (res.code == 200) {
        if (res.data.list.length < 1 && this.pageNum != 1) { //判断，当搜索关键字有内容时，我直接点击分页，会造成关键词列表中没有某某页的数据，那么我就用第一页重新请求一次
          this.pageNum = 1
          this.queryDepartmentList()
          return
        }
        this.departmentData = res.data.list;
        this.total = res.data.total;
      } else {
        this.$message.error(res.message)
      }

    },


    confirmToDelete(id) {
      deleteDepartmentById(id).then((res) => {
        if (res.code == 200) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.queryDepartmentList();
        } else {
          this.$message({
            message: res.message,
            type: "warning",
          });
        }
      });
    },




  }
};
</script>

<style lang="less" scoped>
.TableStyle1 {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__row:not([class*="el-table__row--level-"]) {
      td:first-child {
        padding-left: 24px !important; //一级数据无Child缩进
      }
    }

    .el-table__placeholder {
      margin-left: 3px; //子节点无Child缩进
    }


    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.TableStyle {
  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 20px;

    .el-dialog__body {
      padding: 0 20px;

      .el-divider {
        margin: 20px 0;
      }
    }

    .el-dialog__footer {
      padding: 0;
    }
  }
}

.textBtn {
  span {
    display: block;
    position: relative;

    &:nth-child(n+2) {

      // border-left: 1px solid #aaa;
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}

.menuTable {
  margin-top: 100px;

  // /deep/ .cell {
  //   text-align: left !important;
  // }


}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}



.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.Top {
  position: relative;

  .operation {
    position: absolute;
    left: 15px;
    top: 68px;
  }
}



.formItemStyle {
  margin-bottom: 22px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}



.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}
</style>